package com.anypi;

import java.io.IOException;

import com.pi4j.wiringpi.Spi;

public class SpiRF implements ISpiRF{

	// CS on CE0
	public static final byte WRITE_BURST_CMD = 0x40;
	public static final byte READ_CMD = (byte) 0x80;
	public static final byte READ_BUSRT_CMD = (byte) 0xC0;
	
	private int frequency = 1000000;

	public SpiRF(){
		
		// setup SPI for communication
		try {
			
			Runtime.getRuntime().exec("sudo modprobe spi_bcm2708");
			Runtime.getRuntime().exec("sudo chown `id -u`.`id -g` /dev/spidev0.*");
			

		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	public void setFrequency(int frequency) throws IOException{
		
		this.frequency = frequency;
		int fd = Spi.wiringPiSPISetup(0, frequency); // SPI CLK = 2 Mhz
		if (fd <= -1) {
			System.out.println(" ==>> SPI SETUP FAILED");
			throw new IOException("SPI SETUP FAILED");
		}
	}
	
	public int getFrequency(){
		return frequency;
	}
	
	public void writeRegister(byte register, int data) {

		byte packet[] = new byte[2];
		packet[0] = register; // address byte
		packet[1] = (byte) data; // data

		Spi.wiringPiSPIDataRW(0, packet, 2);

	}

	public boolean writeBusrtRegister(byte addr, byte buffer[], int count) {

		if (buffer.length < count)
			return false;

		else {
			
			byte[] tmp = new byte[count + 1];
			tmp[0] = (byte) (addr + WRITE_BURST_CMD);
			for(int i = 1; i < count+1; i++){
				tmp[i] = buffer[i-1];
			}
			Spi.wiringPiSPIDataRW(0, tmp, count + 1);

			return true;
		}
	}

	public byte readRegister(byte addr) {

		byte packet[] = new byte[2];
		packet[0] = (byte) (READ_CMD + addr); // commande de lecture + addresse
		packet[1] = 0x00;  // dummy
		
		Spi.wiringPiSPIDataRW(0, packet, 2);
		
		return packet[1];
	}

	public boolean readBurstRegister(byte addr, byte buffer[], int count) {

		if (buffer.length < count)
			return false;

		else {

			buffer[0] = (byte) (addr + READ_BUSRT_CMD);
			Spi.wiringPiSPIDataRW(0, buffer, count + 1);

			return true;
		}

	}
	
}
